package com.bw.controller.process;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.process.PiProcess;
import com.bw.resp.ResponseResult;
import com.bw.service.process.IPiProcessService;
import com.bw.utils.excel.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.excelutils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuhao
 * @since 2020-06-16
 */
@RestController
@RequestMapping("/process")
public class PiProcessController {
    @Resource
    IPiProcessService iPiProcessService;

    private final Logger logger= LoggerFactory.getLogger(PiProcessController.class);

    /**
     * 查询工序列表
     * @param currentPage
     * @param pageSize
     * @param piProcess
     * @return com.bw.resp.ResponseResult
     */

    @PostMapping("list/{currentPage}/{pageSize}")
    public ResponseResult list(@PathVariable("currentPage") int currentPage,@PathVariable("pageSize") int pageSize, @RequestBody PiProcess piProcess) { //参数json字符串
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            logger.info("查询列表开始");
            QueryWrapper queryWrapper = new QueryWrapper();
            if (piProcess.getName()!=null && "".equals(piProcess.getName())) {
                queryWrapper.like("name", "%" + piProcess.getName() + "%");
            }
            PageHelper.startPage(currentPage, pageSize);//开启分页查询
            List<PiProcess> piProcesses = iPiProcessService.list(queryWrapper);//列表查询
            PageInfo pageInfo = new PageInfo(piProcesses);//pagehelper封装好的分页实体类，将数据放进去
            result.setResult(pageInfo);
        } catch (Exception e) {
            logger.info("查询失败");
            result.setSuccess(false);
            result.setMessage("查询失败:" + e.toString());
        }
        logger.info("查询列表结束");
        return result;
    }

    /**
     * 添加工序
     * @param piProcess
     * @return com.bw.resp.ResponseResult
     */
    @PostMapping("save")
    public ResponseResult save(@RequestBody PiProcess piProcess) {
        logger.info("添加开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            iPiProcessService.saveOrUpdate(piProcess);
            result.setMessage("保存工序成功");
        } catch (Exception e) {
            logger.info("添加失败");
            result.setSuccess(false);
            result.setMessage("保存工序失败:" + e.toString());
        }
        logger.info("添加结束");
        return result;
    }

    /**
     * 根据Id查询工序，回显
     * @param id
     * @return com.bw.resp.ResponseResult
     */
    @GetMapping("getById/{id}")
    public ResponseResult getById(@PathVariable("id") Long id) {
        logger.info("查询工序开始");
        System.out.println(id+"-----------------");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiProcess piProcess = iPiProcessService.getById(id);
            result.setResult(piProcess);
            result.setMessage("查询工序成功");
        } catch (Exception e) {
            logger.info("查询工序失败");
            result.setSuccess(false);
            result.setMessage("查询工序失败:" + e.toString());
        }
        logger.info("查询工序结束");
        return result;
    }

    /**
     * 编辑工序
     * @param id
     * @return com.bw.resp.ResponseResult
     */
    @GetMapping("updateById/{id}")
    public ResponseResult updateById(@PathVariable("id") Long id) {
        logger.info("修改开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiProcess piProcess = iPiProcessService.getById(id);
            iPiProcessService.saveOrUpdate(piProcess);
            result.setMessage("编辑工序成功");
        } catch (Exception e) {
            logger.info("修改失败");
            result.setSuccess(false);
            result.setMessage("编辑工序失败:" + e.toString());
        }
        logger.info("修改结束");
        return result;
    }

    /**
     * 删除
     * @param id
     * @return com.bw.resp.ResponseResult
     */
    @GetMapping("deleteById/{id}")
    public ResponseResult deleteById(@PathVariable("id") Long id) {
        logger.info("删除开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            iPiProcessService.removeById(id);
            result.setMessage("删除工序成功");
        } catch (Exception e) {
            logger.info("删除失败");
            result.setSuccess(false);
            result.setMessage("删除工序失败:" + e.toString());
        }
        logger.info("删除结束");
        return result;
    }

//    @GetMapping("exportExcel")
//    public void exportExcel(HttpServletResponse response) throws IOException {
//        List<PiProcess> processList = iPiProcessService.list();
//        Workbook wb = new XSSFWorkbook();
//        Sheet sheet = wb.createSheet("联系人数据");
//        Row rowTitle = sheet.createRow(0);
//        String[] titles={"编号","姓名","收费方式","单价","准备工时单价","描述"};
//        Font font = wb.createFont();
//        font.setBold(true);
//        CellStyle cellStyle = wb.createCellStyle();
//        cellStyle.setFont(font);
//        for (int i=0;i<titles.length;i++){
//            Cell titleCell = rowTitle.createCell(i);
//            titleCell.setCellStyle(cellStyle);
//            titleCell.setCellValue(titles[i]);
//        }
//        for(int i=0;i<processList.size();i++){
//            Row row = sheet.createRow(i + 1);
//            row.createCell(0).setCellValue(processList.get(i).getId());
//            row.createCell(2).setCellValue(processList.get(i).getCode());
//            row.createCell(1).setCellValue(processList.get(i).getName());
//            row.createCell(3).setCellValue(processList.get(i).getCType());
//            row.createCell(4).setCellValue((RichTextString) processList.get(i).getPrice());
//            row.createCell(5).setCellValue((RichTextString) processList.get(i).getPrePrice());
//            row.createCell(6).setCellValue(processList.get(i).getRemarks());
//
//        }
//        response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
//        response.setHeader("Content-Disposition","attachment;filename="+new String("工序数据".getBytes(),"iso-8859-1")+".xlsx");
//        wb.write(response.getOutputStream());
//
//    }

    /**
     * 从数据库导出工序
     * @param response
     * @throws Exception
     */
    @GetMapping("exportExcel")
    public void exportExcel(HttpServletResponse response) throws Exception {
        logger.info("导出excel开始");
        List<PiProcess> piProcessList=iPiProcessService.list();
        response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+new String("工序数据".getBytes(),"iso-8859-1")+".xlsx");

        //excel模板的流获取
        ClassPathResource classPathResource=new ClassPathResource("xls/process.xls");
        InputStream inputStream=classPathResource.getInputStream();
        ExcelUtils.addValue("list",piProcessList);
        ExcelUtils.export(inputStream,ExcelUtils.getContext(),response.getOutputStream());
        logger.info("导出结束");
    }

    /**
     * 从Excel表格把数据导入数据库
     * @param file
     * @return com.bw.resp.ResponseResult
     * @throws Exception
     */

    @PostMapping("importExcel")
    public ResponseResult importExcel(MultipartFile file) throws Exception {
        logger.info("导入excel开始");
        ResponseResult responseResult=ResponseResult.SUCCESS();

        try {
            //获取文件后缀
            String ext=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length());
            List<Map> mapList=ExcelUtil.readExcel(ext,file.getInputStream());

            System.out.println(mapList);
            String jsonString= JSON.toJSONString(mapList);//map集合转化为json字符串
            List<PiProcess> piProcesses=JSON.parseArray(jsonString, PiProcess.class);//json字符串转换为list集合
            //添加
            iPiProcessService.saveBatch(piProcesses);
        } catch (IOException e) {
            logger.info("导入失败");
            responseResult.setSuccess(false);
            responseResult.setMessage("导入工序失败:" + e.toString());
        }
        logger.info("导入结束");
        return responseResult;
    }

    /**
     * 查询工序
     * @return
     */
    @GetMapping("processList")
    public ResponseResult processList() {
        logger.info("查询开始");
        ResponseResult responseResult=ResponseResult.SUCCESS();

        try {
            responseResult.setResult(iPiProcessService.list());
        } catch (Exception e) {
            logger.info("查询失败");
            responseResult.setSuccess(false);
            responseResult.setMessage("导入工序失败:" + e.toString());
        }
        logger.info("查询结束");
        return responseResult;
    }




}
